<template>
  <div class="user-list">
    <!-- 搜索和操作栏 -->
    <el-card class="search-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="searchQuery"
            placeholder="搜索用户昵称、手机号..."
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        
        <!-- <el-col :span="4">
          <el-select v-model="statusFilter" placeholder="用户状态" clearable @change="handleSearch">
            <el-option label="全部" value="" />
            <el-option label="活跃用户" value="active" />
            <el-option label="新用户" value="new" />
            <el-option label="沉睡用户" value="inactive" />
          </el-select>
        </el-col> -->
        
        <!-- <el-col :span="6">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleSearch"
          />
        </el-col> -->
        
        <el-col :span="8">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <!-- <el-button type="success" @click="exportUsers">
            <el-icon><Download /></el-icon>
            导出用户
          </el-button> -->
        </el-col>
      </el-row>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>用户列表 (共 {{ total }} 人)</span>
          <div class="header-actions">
            <el-button size="small" @click="loadUsers">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table
        :data="users"
        :loading="loading"
        stripe
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column prop="id" label="ID" width="80" sortable="custom" />
        
        <el-table-column label="用户信息" min-width="200">
          <template #default="scope">
            <div class="user-info">
              <el-avatar :src="scope.row.avatar_url" :size="40">
                {{ scope.row.nickname?.charAt(0) || 'U' }}
              </el-avatar>
              <div class="user-details">
                <div class="nickname">{{ scope.row.nickname || '未设置昵称' }}</div>
                <div class="phone">{{ scope.row.phone || '未绑定手机' }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="treatment_count" label="治疗次数" width="100">
          <template #default="scope">
            <el-tag :type="getTreatmentCountType(scope.row.treatment_count)">
              {{ scope.row.treatment_count }}
            </el-tag>
          </template>
        </el-table-column>
        
     
        
        
        <el-table-column prop="created_at" label="注册时间" width="180" >
          <template #default="scope">
            {{ formatDateTime(scope.row.created_at) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="280" >
          <template #default="scope">
            <el-button size="small" @click="viewUserDetail(scope.row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button size="small" type="primary" @click="openRemoteConfig(scope.row)">
              <el-icon><Setting /></el-icon>
              远程配置
            </el-button>
            <!-- <el-button size="small" type="warning" @click="editUser(scope.row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button> -->
         
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户详情对话框 -->
    <UserDetailDialog
      v-model="showUserDetail"
      :user="selectedUser"
      @refresh="loadUsers"
    />
    
    <!-- 远程配置治疗方案对话框 -->
    <el-dialog
      v-model="remoteConfigVisible"
      title="远程配置治疗方案"
      width="600px"
    >
      <el-form :model="remoteConfigForm" label-width="140px">
        <el-form-item label="模板名称" prop="template_name" :rules="[{ required: true, message: '请输入模板名称', trigger: 'blur' }]">
          <el-input v-model="remoteConfigForm.template_name" placeholder="请输入模板名称" />
        </el-form-item>
        <!-- <el-form-item label="模板类型">
          <el-select v-model="remoteConfigForm.template_type" placeholder="请选择模板类型">
            <el-option label="医院" value="hospital" />
            <el-option label="学校" value="school" />
            <el-option label="企业" value="enterprise" />
            <el-option label="科研" value="research" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="治疗模式">
          <el-select v-model="remoteConfigForm.mode" placeholder="请选择治疗模式">
            <el-option label="tDCS+" value="tDCS+" />
            <el-option label="tDCS-" value="tDCS-" />
            <el-option label="tACS" value="tACS" />
          </el-select>
        </el-form-item>
        <el-form-item label="电流强度(mA)">
          <el-slider 
            v-model="remoteConfigForm.current" 
            :min="0" 
            :max="2" 
            :step="0.01"
            show-input
          />
        </el-form-item>
        <el-form-item label="治疗时间(分钟)">
          <el-input-number 
            v-model="remoteConfigForm.duration" 
            :min="10"
            :step="5" 
            :max="30" 
          />
        </el-form-item>
        <el-form-item label="频率(Hz)" v-if="remoteConfigForm.mode === 'tACS'">
          <el-input-number 
            v-model="remoteConfigForm.frequency" 
            :min="0.5" 
            :max="100" 
            :step="0.5"
          />
        </el-form-item>
       
        <el-form-item label="备注">
          <el-input 
            v-model="remoteConfigForm.remark" 
            type="textarea" 
            placeholder="请输入配置备注"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="remoteConfigVisible = false">取消</el-button>
          <el-button type="primary" @click="sendRemoteConfig">发送配置</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 用户编辑对话框 -->
    <UserEditDialog
      v-model="showUserEdit"
      :user="selectedUser"
      @refresh="loadUsers"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Download,
  View,
  Edit,
  ArrowDown,
  Setting
} from '@element-plus/icons-vue'
import UserDetailDialog from '@/components/users/UserDetailDialog.vue'
import UserEditDialog from '@/components/users/UserEditDialog.vue'
import { getUserList, updateUser, createRemoteTreatmentTemplate } from '@/api/user'
import { formatDateTime } from '@/utils/format'

// 响应式数据
const users = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

// 搜索条件
const searchQuery = ref('')
const statusFilter = ref('')
const dateRange = ref([])
const sortField = ref('')
const sortOrder = ref('')

// 对话框状态
const showUserDetail = ref(false)
const showUserEdit = ref(false)
const selectedUser = ref(null)
const selectedUsers = ref([])
const remoteConfigVisible = ref(false)

// 远程配置表单
const remoteConfigForm = ref({
  template_name: '',
  template_type: 'hospital',
  mode: 'tDCS+',
  current: 1.0,
  duration: 20,
  frequency: 10.0,
  is_default: false,
  remark: ''
})

// 当前选中的用户
const currentUser = ref(null)

// 计算属性
const searchParams = computed(() => ({
  page: currentPage.value,
  limit: pageSize.value,
  search: searchQuery.value,
  status: statusFilter.value,
  start_date: dateRange.value?.[0],
  end_date: dateRange.value?.[1],
  sort_field: sortField.value,
  sort_order: sortOrder.value
}))

// 方法
const loadUsers = async () => {
  loading.value = true
  try {
    // 修复参数不匹配问题
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchQuery.value,
      status: statusFilter.value
    }
    
    const response: any = await getUserList(params)
    
    users.value = response.records || response.data
    total.value = response.total || (response.pagination ? response.pagination.total : 0)
  } catch (error) {
    
    ElMessage.error('加载用户列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadUsers()
}

const resetSearch = () => {
  searchQuery.value = ''
  statusFilter.value = ''
  dateRange.value = []
  sortField.value = ''
  sortOrder.value = ''
  handleSearch()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadUsers()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadUsers()
}

const handleSortChange = ({ prop, order }) => {
  sortField.value = prop
  sortOrder.value = order === 'ascending' ? 'asc' : 'desc'
  loadUsers()
}

const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

const viewUserDetail = (user) => {
  selectedUser.value = user
  showUserDetail.value = true
}

const editUser = (user) => {
  selectedUser.value = user
  showUserEdit.value = true
}

// 打开远程配置对话框
const openRemoteConfig = (user) => {
  currentUser.value = user
  // 重置表单
  remoteConfigForm.value = {
    template_name: '',
    template_type: 'hospital',
    mode: 'tDCS+',
    current: 1.0,
    duration: 20,
    frequency: 10.0,
    is_default: false,
    remark: ''
  }
  remoteConfigVisible.value = true
}

// 发送远程配置
const sendRemoteConfig = async () => {
  try {
    // 验证表单
    if (!remoteConfigForm.value.template_name) {
      ElMessage.error('请输入模板名称')
      return
    }
    
    // 构造发送到后端的数据
    const configData = {
      user_id: currentUser.value.id,
      template_name: remoteConfigForm.value.template_name,
      template_type: remoteConfigForm.value.template_type,
      treatment_mode: remoteConfigForm.value.mode,
      current_intensity: remoteConfigForm.value.current,
      treatment_duration: remoteConfigForm.value.duration,
      frequency: remoteConfigForm.value.mode === 'tACS' ? remoteConfigForm.value.frequency : 0,
      is_default: remoteConfigForm.value.is_default,
      remark: remoteConfigForm.value.remark
    }
    
    // 调用API发送远程配置
    await createRemoteTreatmentTemplate(configData)
    
    ElMessage.success('远程治疗方案配置成功')
    remoteConfigVisible.value = false
  } catch (error) {
    ElMessage.error('发送远程配置失败: ' + (error as any).message || '')
    console.error(error)
  }
}

const handleUserAction = async ({ action, user }) => {
  switch (action) {
    case 'ban':
      await handleBanUser(user)
      break
    case 'reset':
      await handleResetPassword(user)
      break
    case 'export':
      await handleExportUserData(user)
      break
  }
}

const handleBanUser = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要禁用用户 "${user.nickname}" 吗？这将禁止该用户登录系统。`,
      '确认禁用用户',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 更新用户状态为禁用
    const updatedUser = { ...user, status: 'inactive' }
    await updateUser(user.id, updatedUser)
    ElMessage.success('用户禁用成功')
    loadUsers()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('禁用用户失败')
    }
  }
}

const handleResetPassword = async (user) => {
  ElMessage.info('重置密码功能开发中...')
}

const handleExportUserData = async (user) => {
  try {
    ElMessage.success('用户数据导出成功')
  } catch (error) {
    ElMessage.error('导出用户数据失败')
  }
}

const exportUsers = async () => {
  try {
    const userIds = selectedUsers.value.map(user => user.id)
    ElMessage.success('用户数据导出成功')
  } catch (error) {
    ElMessage.error('导出用户数据失败')
  }
}

// 辅助方法
const getTreatmentCountType = (count: number) => {
  if (count === 0) return 'info'
  if (count < 5) return 'warning'
  if (count < 20) return 'success'
  return 'danger'
}

const getUserStatusType = (user) => {
  const daysSinceLogin = user.last_login 
    ? Math.floor((Date.now() - new Date(user.last_login).getTime()) / (1000 * 60 * 60 * 24))
    : 999
  
  if (daysSinceLogin <= 7) return 'success'
  if (daysSinceLogin <= 30) return 'warning'
  return 'danger'
}

const getUserStatusText = (user) => {
  const daysSinceLogin = user.last_login 
    ? Math.floor((Date.now() - new Date(user.last_login).getTime()) / (1000 * 60 * 60 * 24))
    : 999
  
  if (daysSinceLogin <= 7) return '活跃'
  if (daysSinceLogin <= 30) return '一般'
  return '沉睡'
}

// 监听治疗模式变化
const handleModeChange = (newMode) => {
  if (newMode !== 'tACS') {
    remoteConfigForm.value.frequency = 0
  } else if (!remoteConfigForm.value.frequency) {
    remoteConfigForm.value.frequency = 10.0
  }
}

// 生命周期
onMounted(() => {
  loadUsers()
})
</script>

<style scoped lang="scss">
.user-list {
  padding: 20px;
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-actions {
        display: flex;
        gap: 10px;
      }
    }
    
    .user-info {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .user-details {
        .nickname {
          font-weight: 500;
          color: #303133;
        }
        
        .phone {
          font-size: 12px;
          color: #909399;
          margin-top: 2px;
        }
      }
    }
    
    .pagination-wrapper {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }
  }
}
</style>